<?php
/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/10/27
 * Time: 16:20
 * Comment: ''
 */

namespace App\Jobs;

use App\Repository\ApplyLogRepo;
use App\Repository\MerchantsCastingLogRepo;
use App\Repository\SpecialRepo;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MerchansCastingJob extends Job
{

    use  InteractsWithQueue, Queueable, SerializesModels;

    // 铸造流水日志
    protected $merchants_casting_log;
    //  藏品ID
    protected $special_id;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 2;

    /**
     * 任务失败前允许的最大异常数
     *
     * @var int
     */
    public $maxExceptions = 2;

    public function __construct(array $merchants_casting_log,int $special_id)
    {
        $this->merchants_casting_log = $merchants_casting_log;
        $this->special_id = $special_id;
    }

    public function handle()
    {
        $log = $this->merchants_casting_log;
        Log::info("[藏品铸造申请消耗日志]铸造流水参数".json_encode($log,JSON_UNESCAPED_UNICODE));
        $special_id = $this->special_id;
        Log::info("[藏品铸造申请消耗日志]更新指定藏品ID：".$special_id);

        DB::beginTransaction();
        try {
            // 保存流水记录
            $logId = MerchantsCastingLogRepo::getInstance()->saveLog($log);
            // 藏品铸造更新流水号
            $specialId = SpecialRepo::getInstance()->save(['serial_number'=>$log['serial_number'],'update_time'=>date('Y-m-d H:i:s')],$special_id);

            if ($logId && $specialId)
            {
                DB::commit();
                return;
            }
            DB::rollBack();
        }catch (\Exception $e)
        {
            Log::info("[藏品铸造申请消耗日志]异步任务服务异常：".$e->getMessage());
            DB::rollBack();
            return;
        }

    }

}
